package com.project.springboot.poi;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.junit.jupiter.api.Test;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * description: 测试使用poi批量导出Excel
 * @author 朱正磊
 * @date 2025-05-06 10:14:12
 */
public class PoiTest2 {

    @Test
    void test() {
        // 定义要导出的数据量
        int rowCount = 100000;
        int columnCount = 10;

        // 创建一个 SXSSFWorkbook 对象，设置内存中保留 100 行数据，超出则写入磁盘
        try (Workbook workbook = new SXSSFWorkbook(100);
             FileOutputStream fileOut = new FileOutputStream("large_data_export2.xlsx")) {

            // 创建一个工作表
            Sheet sheet = workbook.createSheet("Large Data");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < columnCount; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue("Column " + (i + 1));
            }

            // 填充数据
            for (int i = 1; i <= rowCount; i++) {
                Row row = sheet.createRow(i);
                for (int j = 0; j < columnCount; j++) {
                    Cell cell = row.createCell(j);
                    cell.setCellValue("Data " + i + "-" + (j + 1));
                }
            }

            // 写入文件
            workbook.write(fileOut);
            System.out.println("数据导出成功！");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
